var logger = require('../config/log').logger('admin');
var bmService = require('../service/bookMarkService.js');
var BookMark = require('../models/bookMark.js');

var Param = function(user, type) {
    this.user = user;
    this.type = type;
}

exports.admin = function(req, res) {
    var param = new Param(req.user);
    res.render('admin/main', param);
}

exports.adminBookMark = function(req, res) {
    var param = new Param(req.user, 'bm');
    BookMark.all(function(marks, err) {
        logger.debug(marks);
        Param.prototype.bookMarks = null;
        param.bookMarks = marks;
        if (err) {
            errStr = 'Get Bookmarks From DB err: ' + err;
            logger.error(errStr);
        }
        res.render('admin/main', param);
    });
}

exports.adminBookMarkXml = function(req, res) {
    var param = new Param(req.user, 'bmxml');
    bmService.getBookMarkXml(function(json) {
        logger.debug(JSON.stringify(json['xml_api_reply']['bookmarks']));
        Param.prototype.bookMarks = null;
        param.bookMarks = json['xml_api_reply']['bookmarks']['bookmark'];
        res.render('admin/main', param);
    });
}

exports.doBookmarkUpdate = function(req, res) {
    var errStr;
    var success = true;
    // logical code 
    BookMark.createTable(function(err) {
        if (err) {
            success = false;
            errStr = 'Open index and create table err: ' + err;
            logger.error(errStr);
        } else {
            bmService.getBookMarkXml(function(json) {
                var bookMarks = json['xml_api_reply']['bookmarks']['bookmark'];
                BookMark.saveAll(bookMarks, function(err) {
                    if (err) {
                        success = false;
                        errStr = 'Do Bookmark Update and save err: ' + err;
                        logger.error(errStr);
                    };
                });
            });
        };
    });
    // return
    res.send({
        'success': success,
        'err': errStr
    });
}

exports.login = function(req, res) {
    res.render('admin/login', {
        user: req.user
    });
}

exports.logout = function(req, res) {
    req.logout();
    res.redirect('/');
}

// Simple route middleware to ensure user is authenticated.
// Use this route middleware on any resource that needs to be protected. If
// the request is authenticated (typically via a persistent login session),
// the request will proceed. Otherwise, the user will be redirected to the
// login page.
exports.ensureAuthenticated = function(req, res, next) {
    //if (req.isAuthenticated()) {
    return next();
    //}
    //res.redirect('/login')
}